//
//  LXComposeViewController.swift
//  weibo
//
//  Created by lixin on 16/4/23.
//  Copyright © 2016年 lixin. All rights reserved.
//

import UIKit

import SVProgressHUD

class LXComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        setUI()
    }

    // MARK: - 设置视图
    private func setUI(){
        
        setNav()
        
        view.backgroundColor = UIColor.whiteColor()
       
        view.addSubview(composeTextView)
        
        view.addSubview(composeToolBar)
        
        composeTextView.addSubview(composePictureView)
       
        // 在ios7以后 系统检测你如果有导航栏 他直接叫你显示的文字下移
        composeTextView.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(view).offset(UIEdgeInsetsZero)
        }
        
        composeToolBar.snp_makeConstraints { (make) -> Void in
            
            make.leading.trailing.bottom.equalTo(view)
            
            make.height.equalTo(44)
        }
        
        composePictureView.snp_makeConstraints { (make) -> Void in
            
            make.size.equalTo(CGSize(width: SCREENW - 20, height: SCREENW - 20))
            
            make.leading.equalTo(10)
            
            make.top.equalTo(composeTextView).offset(100)
        }
        
        //监听toolbar按钮点击
        composeToolBar.composeToolBarColsure = {[weak self](type: LXComposeToolbarType) in
            switch type{
                
            case .Picture:
                
                self?.selectImage()
                
            case .Mention:
                
                print("@")
                
            case .Trend:
                
                print("#")
                
            case .Emoticon:
                
                self?.switchKeyborad()
                
            case .Add:
                
                print("+")
            }
        }
        
        //弹出图片控制器
        composePictureView.composePictureViewClosure = { [weak self] in
            
            self?.selectImage()
            
        }
        
        //监听键盘弹出frame改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(LXComposeViewController.keyboardWillChangeFrame(_:)), name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        //表情键盘删除按钮通知接收
         NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(LXComposeViewController.deleteBtnClick), name: "deleteNoti", object: nil)
        
        //表情键盘表情按钮通知接收
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(LXComposeViewController.emoticonBtnClick(_:)), name: "EmoticonButtonNoti", object: nil)

        
    }
    
    //表情键盘删除按钮点击事件
    func deleteBtnClick(){
        
       composeTextView.deleteBackward()
    }
    
    //表情键盘表情按钮点击事件
    func emoticonBtnClick(noti: NSNotification){
    
        guard let emoticon = noti.object as? LXEmoticon else{
            return
        }
        
        if emoticon.isEmoji{
            
            // 把十六进制的字符串转成emoji表情
            let code = ((emoticon.code ?? "") as NSString).emoji()
            
            //插入emoji表情
            composeTextView.insertText(code)
            
        }else{
            
            //以前的富文本
            let oldAttr = NSMutableAttributedString(attributedString: composeTextView.attributedText)
            
            //初始化一个image
            let path = "\(emoticon.path ?? "")\(emoticon.png ?? "")"
            
            let image = UIImage(named: path, inBundle: LXEmoticonTools.sharedTools.emoticonBundle, compatibleWithTraitCollection: nil)
            
            //行高
            let lineHeight = composeTextView.font!.lineHeight
            
            //初始化文本附件
            let att = LXTextAttachment()
            
            att.emoticon = emoticon
            
            att.bounds = CGRect(x: 0, y: -4, width: lineHeight, height: lineHeight)
            
            att.image = image
            
            //不可变富文本
            let attr = NSAttributedString(attachment: att)
            
            let selectedRange = composeTextView.selectedRange
            
            // 替换选中部分的富文本
            oldAttr.replaceCharactersInRange(selectedRange, withAttributedString: attr)
            
            // 设置富文本字体
            oldAttr.addAttribute(NSFontAttributeName, value: composeTextView.font!, range: NSMakeRange(0, oldAttr.length))
            
            composeTextView.attributedText = oldAttr
            
            composeTextView.selectedRange = NSMakeRange(selectedRange.location + 1, 0)
            
            //发送通知，隐藏占位文字
            NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: nil)
            
            composeTextView.delegate?.textViewDidChange!(composeTextView)
        }
    }
    
    //监听键盘frame改变方法
    func keyboardWillChangeFrame(noti: NSNotification){
        
        let rect = (noti.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).CGRectValue()
      
        composeToolBar.snp_updateConstraints { (make) -> Void in
            
            make.bottom.equalTo(view).offset(rect.origin.y - SCREENH)
        }
        
        UIView.animateWithDuration(0.25) { () -> Void in
            
            self.view.layoutIfNeeded()
        }
    }
    
    // MARK: - 设置导航栏
    private func setNav(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(LXComposeViewController.cancelBtnClick))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(LXComposeViewController.sendBtnClick))
        
        navigationItem.rightBarButtonItem?.enabled = false
        
        navigationItem.titleView = titleView
        
    }
    
    //MARK: - 监听方法
    @objc private func cancelBtnClick(){
        
        // 取消composeTextView的第一响应
        composeTextView.resignFirstResponder()
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func sendBtnClick(){
        
        var result: String = String()
        
        composeTextView.attributedText.enumerateAttributesInRange(NSMakeRange(0, composeTextView.attributedText.length), options: []) { (dictInfo, range, _) -> Void in
            
            if let att = dictInfo["NSAttachment"] as? LXTextAttachment{
                
                result += att.emoticon?.chs ?? ""
                
            }else{
                
                let name = (self.composeTextView.attributedText.string as NSString).substringWithRange(range)
                
                result += name
            }
        }
        
        if composePictureView.images.count != 0{//有图
            
            upload(result)
            
        }else{
            
            update(result)
        }

    }
    
    // MARK: - 懒加载控件
    private lazy var titleView: UILabel = {
        
        let name = LXUserAccountTools.sharedTools.userAccount?.screen_name ?? ""
        
        let titleString = "发微博\n\(name)"
        
        let attr = NSMutableAttributedString(string: titleString)//富文本
        
        let range = (titleString as NSString).rangeOfString(name)
        
        attr.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(12), range: range)
        
        attr.addAttribute(NSForegroundColorAttributeName, value: ThemeColor, range: range)
        
        let label = UILabel(textColor: UIColor.darkGrayColor(), textFont: 15)
        
        label.attributedText = attr
        
        label.numberOfLines = 0
        
        label.textAlignment = .Center
        
        label.sizeToFit()
        
        return label
    }()
    
    //文本输入框
    private lazy var composeTextView: LXComposeTextView = {
        
        let view = LXComposeTextView()
        
        view.font = UIFont.systemFontOfSize(16)
        
        view.delegate = self
        
        view.placeholder = "请输入您要发表的内容"
        
        view.alwaysBounceVertical = true
        
        return view
    }()
    
    private lazy var composeToolBar: LXComposeToolbar = LXComposeToolbar()
    
    private lazy var composePictureView: LXComposePictureView = LXComposePictureView()
    
    //自定义表情键盘
    private lazy var emoticonKeyboard: LXEmoticonKeyboardView = {
        
        let view = LXEmoticonKeyboardView()
        
        view.frame = CGRect(x: 0, y: 0, width: SCREENW, height: 216)
        
        return view
    }()
    
    deinit{
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    
}

//MARK: - 发布微博
extension LXComposeViewController{
    
    //发布文字微博
    func update(status: String){
        
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        
        let params = [
            "access_token": LXUserAccountTools.sharedTools.accessToken!,
            "status":status
        ]
        
        LXNetworkTools.sharedTools.request(LXRequestMethod.POST, urlString: urlString, params: params) { (response, error) -> () in
            if error != nil{
                
                SVProgressHUD.showErrorWithStatus("发送失败")
                return
            }
            
            SVProgressHUD.showSuccessWithStatus("发送成功")
            
            self.cancelBtnClick()
        }
    }
    
    //发布文字和图片微博
    func upload(status: String){
        
        let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
        
        let params = [
            
            "access_token": LXUserAccountTools.sharedTools.accessToken!,
            
            "status":status
        ]
        
        LXNetworkTools.sharedTools.POST(urlString, parameters: params, constructingBodyWithBlock: { (formdata) -> Void in
        
            // 上传多张图片
            for i in self.composePictureView.images {
                
                let data = UIImagePNGRepresentation(i)!
                
                formdata.appendPartWithFileData(data, name: "pic", fileName: "xxx", mimeType: "image/jpeg")
            }
            
            }, progress: nil, success: { (_, response) -> Void in
                
                SVProgressHUD.showSuccessWithStatus("发送成功")
                
                self.cancelBtnClick()
                
        }) { (_, error) -> Void in
            
            SVProgressHUD.showErrorWithStatus("发送失败")
        }
    }
}

// MARK: - UITextView的代理方法
extension LXComposeViewController: UITextViewDelegate{
    
    func textViewDidChange(textView: UITextView) {
        
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        composeTextView.resignFirstResponder()
    }
}
// MARK: - toolbar的按钮点击事件
extension LXComposeViewController{
    
    func selectImage() {
        
        let pickerVc =  UIImagePickerController()
        
        pickerVc.delegate = self
        
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera){
            
        }else{
            
            presentViewController(pickerVc, animated: true, completion: nil)
        }
    }
    
    //切换键盘
    func switchKeyborad(){
        
        if composeTextView.inputView == nil{
            
            composeTextView.inputView = emoticonKeyboard
            
            composeToolBar.isEmoticon = true
            
        }else{
            
            composeTextView.inputView = nil
            
            composeToolBar.isEmoticon = false
        }
        
        composeTextView.reloadInputViews()
        
        composeTextView.becomeFirstResponder()
    }
    
}

//MARK: - LXComposeViewController的代理和数据源方法
extension LXComposeViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
      
        composePictureView.addImage(getImageScale(image, width: 600))
        
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
    //压缩图片
    func getImageScale(image: UIImage, width: CGFloat) -> UIImage{
       
        if image.size.width < width{
            
            return image
        }
       
        let height = (image.size.height * width) / image.size.width
        
        UIGraphicsBeginImageContext(CGSize(width: width, height: height))
        
        image.drawInRect(CGRect(x: 0, y: 0, width: width, height: height))
        
        let result = UIGraphicsGetImageFromCurrentImageContext()
        
        UIGraphicsEndImageContext()
        
        return result
    }
}
